#ifndef _THREAD
#define _THREAD

#include <windows.h>
#include <process.h>

class CThread
{
public:
	CThread()
	{
		m_Handle = 0;
		m_ThreadID = 0;
		m_IsRun = false;
		m_CloseEvent = NULL;
	}

	virtual ~CThread()
	{

	}

	bool Start()
	{
		if ( true == m_IsRun )
			return false;

		m_Handle = (HANDLE)_beginthreadex( NULL, 0, ThreadFunction, (LPVOID)this, 0, &m_ThreadID );
		if ( NULL == m_Handle )
		{
			return false;
		}

		m_IsRun = true;
		return true;
	}

	void Stop()
	{
		m_IsRun = false;
		m_CloseEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
		if ( WAIT_TIMEOUT == WaitForMultipleObjects( 1, &m_CloseEvent, FALSE, 100 ) )
			TerminateThread( m_Handle, 0 );

		CloseHandle( m_CloseEvent );
		m_CloseEvent = NULL;
	}

	virtual void Run() = 0;

protected:
	void Finished()
	{
		if ( m_CloseEvent != NULL )
			SetEvent(m_CloseEvent);
	}

	bool	m_IsRun;
	HANDLE	m_CloseEvent;

private:
	CThread( const CThread& t );
	CThread &operator=( const CThread& t );

	static unsigned int WINAPI ThreadFunction( void* lpParam )
	{
		CThread* pThis = (CThread*)lpParam;
		pThis->Run();
		return 1;
	}

	HANDLE	m_Handle;
	UINT	m_ThreadID;
};

#endif